# apps/audit/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import AuditLog

User = get_user_model()

@admin.register(AuditLog)
class AuditLogAdmin(admin.ModelAdmin):
    list_display = (
        'timestamp', 'username', 'action', 'model_name',
        'object_repr', 'ip_address', 'user_agent_preview'
    )
    list_filter = ('action', 'model_name', 'timestamp', 'tenant')
    search_fields = ('username', 'object_id', 'object_repr', 'ip_address')
    readonly_fields = [f.name for f in AuditLog._meta.fields]
    date_hierarchy = 'timestamp'
    ordering = ('-timestamp',)
    list_per_page = 30

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    @admin.display(description="User Agent (Preview)")
    def user_agent_preview(self, obj):
        return (obj.user_agent[:50] + "...") if obj.user_agent and len(obj.user_agent) > 50 else obj.user_agent

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # 多租户支持：仅显示当前租户日志
        if hasattr(request.user, 'tenant') and request.user.tenant:
            return qs.filter(tenant=request.user.tenant)
        return qs